package sensorgui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.Iterator;

import java.util.List;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class GridView extends JPanel {

	private final int worldSizeX;
	private final int worldSizeY;
	private final int squareHeight;
    private final int squareWidth;
	private final int gridLineWidth;
	private final int xDimension;
	private final int yDimension;
	private final Color gridLineColour;

    private Grid sensorGrid;

	public GridView(Grid sensorGrid) {
		this.sensorGrid = sensorGrid;
		this.setDoubleBuffered(true);

		worldSizeX = sensorGrid.getXSquares();
		worldSizeY = sensorGrid.getYSquares();
		squareHeight = sensorGrid.getSquareHeight();
                squareWidth = sensorGrid.getSquaresWidth();

		gridLineWidth = 1;
		gridLineColour = Color.LIGHT_GRAY;
		// Work out the on-screen size of the grid
		xDimension = worldSizeX * squareWidth + (worldSizeX - 1) * gridLineWidth;
		yDimension = worldSizeY * squareHeight + (worldSizeY - 1) * gridLineWidth;
		this.setPreferredSize(new Dimension(xDimension, yDimension));
		this.setBackground(Color.WHITE);
		// Get all the objects in the grid and create their visual equivalents
		// Question: should this be some kind of factory pattern?
               
		
	}
	
	// Override the paint method to draw the grid and its contents
	public void paint(Graphics g) {
		super.paint(g);
		// Cast to Graphics2D to access advanced features (anti-aliasing, gradient fills)
		Graphics2D g2d = (Graphics2D)g;
		// Turn on graphical anti aliasing
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		// Draw the grid lines
		g2d.setColor(gridLineColour);
		// Draw the vertical lines
		int xPos = squareWidth;
		for (int i = 1; i < worldSizeX; i++) {
			g2d.fillRect(xPos, 0, gridLineWidth, yDimension);
			xPos += gridLineWidth + squareWidth;
		}
		// Draw the horizontal lines
		int yPos = squareHeight;
		for (int i = 1; i < worldSizeY; i++) {
			g2d.fillRect(0, yPos, xDimension, gridLineWidth);
			yPos += gridLineWidth + squareHeight;
		}

        List sensors = sensorGrid.getSensors();
                //sensors.iterator()
        Iterator<Sensor> iterator = sensors.iterator();
		while (iterator.hasNext()) {
                    Sensor sr = iterator.next();
                    if (sr!=null){
                        SensorView sv = new SensorView(sr);
                        sv.paintSensor(g);
                    }
        }
		
	}
}
